<?php
// 确定配置键名，默认为'subscribe-form'
$configKey = isset($configKey) ? $configKey : 'subscribe-form';
// 订阅默认配置
$defaultConfig = [
    'section_id' => $configKey,
    'section_pretitle' => '订阅',
    'section_title' => '订阅我们的通讯',
    'section_subtitle' => '获取最新资讯、优惠活动和行业洞察，直接发送到您的邮箱',
    'placeholder' => '输入您的邮箱地址',
    'button_text' => '立即订阅',
    'form_action' => '/subscribe.php',
    'form_method' => 'post',
    'privacy_note' => '我们尊重您的隐私，不会向第三方分享您的信息',
    'success_message' => '订阅成功！感谢您的关注。',
    'error_message' => '订阅失败，请检查您的邮箱地址后重试',
    'validation' => [
        'email_pattern' => '/^[^\s@]+@[^\s@]+\.[^\s@]+$/',
        'email_error' => '请输入有效的邮箱地址'
    ],
    'classes' => [
        'container' => 'bg-gradient-to-br from-primary to-blue-700 rounded-xl shadow-sm p-6 mb-8 text-white',
        'title' => 'text-xl font-bold mb-2',
        'subtitle' => 'opacity-90 mb-6',
        'input' => 'w-full px-4 py-3 rounded-lg focus:outline-none focus:ring-2 focus:ring-white/50 text-gray-800',
        'button' => 'w-full bg-white text-primary font-medium py-3 px-4 rounded-lg hover:bg-gray-100 transition-colors duration-300 flex items-center justify-center',
        'privacy_note' => 'text-xs opacity-80 text-center',
        'success_message' => 'hidden mt-4 p-4 bg-green-500/20 border border-green-500/30 rounded-lg text-green-400 text-center',
        'error_message' => 'hidden mt-4 p-4 bg-red-500/20 border border-red-500/30 rounded-lg text-red-400 text-center'
    ],
    // 新增texts字段存储所有文本信息
    'texts' => [
        'email_required' => '邮箱地址为必填项',
        'subscribing' => '订阅中...',
        'network_error' => '网络连接错误，请稍后重试',
        'default_error' => '发生错误，请重试'
    ]
];


// 合并配置（全局配置优先于默认配置）
$data = array_merge($defaultConfig, $pageConfig['components'][$configKey] ?? []);
?>

<div id="<?php echo htmlspecialchars($data['section_id']); ?>" class="<?php echo htmlspecialchars($data['classes']['container']); ?>">
    <?php if (!empty($data['section_pretitle'])): ?>
        <div class="text-sm uppercase tracking-wider opacity-80 mb-2">
            <?php echo htmlspecialchars($data['section_pretitle']); ?>
        </div>
    <?php endif; ?>
    
    <h3 class="<?php echo htmlspecialchars($data['classes']['title']); ?>">
        <?php echo htmlspecialchars($data['section_title']); ?>
    </h3>
    
    <p class="<?php echo htmlspecialchars($data['classes']['subtitle']); ?>">
        <?php echo htmlspecialchars($data['section_subtitle']); ?>
    </p>
    
    <form 
        action="<?php echo htmlspecialchars($data['form_action']); ?>" 
        method="<?php echo htmlspecialchars($data['form_method']); ?>"
        class="space-y-3"
        id="<?php echo htmlspecialchars($data['section_id']); ?>-form"
        novalidate
    >
        <div class="form-group">
            <input 
                type="email" 
                name="email"
                placeholder="<?php echo htmlspecialchars($data['placeholder']); ?>"
                class="<?php echo htmlspecialchars($data['classes']['input']); ?>"
                required
                data-validation="<?php echo htmlspecialchars(json_encode($data['validation'] ?? [])); ?>"
            >
            <div class="error-message text-red-300 text-sm mt-1 hidden"></div>
        </div>
        
        <button 
            type="submit"
            class="<?php echo htmlspecialchars($data['classes']['button']); ?>"
            id="<?php echo htmlspecialchars($data['section_id']); ?>-submit"
        >
            <span id="<?php echo htmlspecialchars($data['section_id']); ?>-submit-text">
                <?php echo htmlspecialchars($data['button_text']); ?>
            </span>
            <i class="fa fa-paper-plane ml-2"></i>
            <div id="<?php echo htmlspecialchars($data['section_id']); ?>-loading" class="ml-2 hidden">
                <i class="fa fa-spinner fa-spin"></i>
            </div>
        </button>
        
        <p class="<?php echo htmlspecialchars($data['classes']['privacy_note']); ?>">
            <?php echo htmlspecialchars($data['privacy_note']); ?>
        </p>
    </form>
    
    <!-- 状态消息 -->
    <div 
        id="<?php echo htmlspecialchars($data['section_id']); ?>-success" 
        class="<?php echo htmlspecialchars($data['classes']['success_message']); ?>"
    >
        <?php echo htmlspecialchars($data['success_message']); ?>
    </div>
    
    <div 
        id="<?php echo htmlspecialchars($data['section_id']); ?>-error" 
        class="<?php echo htmlspecialchars($data['classes']['error_message']); ?>"
    >
        <?php echo htmlspecialchars($data['error_message']); ?>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 从PHP配置获取所有数据，包括texts字段
    const config = <?php echo json_encode($data); ?>;
    const formId = config.section_id + '-form';
    const form = document.getElementById(formId);
    
    if (!form) return;
    
    // 获取DOM元素
    const submitButton = document.getElementById(config.section_id + '-submit');
    const submitText = document.getElementById(config.section_id + '-submit-text');
    const loadingIndicator = document.getElementById(config.section_id + '-loading');
    const successMessage = document.getElementById(config.section_id + '-success');
    const errorMessage = document.getElementById(config.section_id + '-error');
    const emailInput = form.querySelector('input[name="email"]');
    
    // 重置表单状态
    function resetFormState() {
        successMessage.classList.add('hidden');
        errorMessage.classList.add('hidden');
        
        if (emailInput) {
            emailInput.classList.remove('border-red-500');
            const errorEl = emailInput.closest('.form-group').querySelector('.error-message');
            if (errorEl) errorEl.classList.add('hidden');
        }
    }
    
    // 验证邮箱
    function validateEmail() {
        const validation = emailInput.dataset.validation ? JSON.parse(emailInput.dataset.validation) : {};
        const value = emailInput.value.trim();
        let isValid = true;
        // 使用配置中的文本信息
        let errorMsg = validation.email_error || config.texts.default_error;
        
        if (!value) {
            isValid = false;
            errorMsg = config.texts.email_required;
        } else if (validation.email_pattern && !new RegExp(validation.email_pattern).test(value)) {
            isValid = false;
        }
        
        const errorEl = emailInput.closest('.form-group').querySelector('.error-message');
        if (!isValid) {
            emailInput.classList.add('border-red-500');
            if (errorEl) {
                errorEl.textContent = errorMsg;
                errorEl.classList.remove('hidden');
            }
        } else {
            emailInput.classList.remove('border-red-500');
            if (errorEl) errorEl.classList.add('hidden');
        }
        
        return isValid;
    }
    
    // 绑定验证事件
    if (emailInput) {
        emailInput.addEventListener('input', validateEmail);
        emailInput.addEventListener('blur', validateEmail);
    }
    
    // 表单提交处理
    form.addEventListener('submit', async function(e) {
        e.preventDefault();
        resetFormState();
        
        // 客户端验证
        if (!validateEmail()) {
            emailInput.focus();
            return;
        }
        
        // 显示加载状态，使用配置中的文本
        submitButton.disabled = true;
        submitText.textContent = config.texts.subscribing;
        loadingIndicator.classList.remove('hidden');
        
        try {
            // 构建表单数据
            const formData = new FormData(form);
            
            // 提交表单
            const response = await fetch(form.action, {
                method: form.method,
                body: formData,
                headers: {
                    'Accept': 'application/json'
                }
            });
            
            const result = await response.json();
            
            if (response.ok && result.success) {
                // 订阅成功
                successMessage.classList.remove('hidden');
                form.reset();
            } else {
                // 订阅失败，使用配置中的文本
                errorMessage.classList.remove('hidden');
                errorMessage.textContent = result.message || config.error_message || config.texts.default_error;
            }
        } catch (error) {
            // 网络错误，使用配置中的文本
            errorMessage.classList.remove('hidden');
            errorMessage.textContent = config.texts.network_error;
            console.error('订阅请求错误:', error);
        } finally {
            // 恢复状态
            submitButton.disabled = false;
            submitText.textContent = config.button_text;
            loadingIndicator.classList.add('hidden');
        }
    });
});
</script>
    